package com.lhd_gm.scheduledtasksystem.utils;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

// 编译类工具类
public class DynamicCodeCompiler {
    // .java文件输出路径
    private static final String javaPath = "ScheduledTaskSystem/src/main/com/lhd_gm/scheduledtasksystem/job";
    // .class文件输出路径
    private static final String classPath = "ScheduledTaskSystem/target/classes";

    public static Class<?> compile(String className, String code) throws Exception {
        // 1. 定义目录
        String projectDir = System.getProperty("user.dir");
        Path sourceDir = Paths.get(projectDir, javaPath);
        Path outputDir = Paths.get(projectDir, classPath);
        Files.createDirectories(sourceDir);
        Files.createDirectories(outputDir);

        // 2. 生成源码文件
        File sourceFile = new File(sourceDir.toFile(), className + ".java");
        Files.write(sourceFile.toPath(), code.getBytes(StandardCharsets.UTF_8));

        // 3. 编译
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        // 获取当前项目的类路径
        String classpath = System.getProperty("java.class.path");
        int result = compiler.run(null, null, null, "-classpath", classpath, "-d", outputDir.toString(), sourceFile.getAbsolutePath());
        if (result != 0) {
            throw new RuntimeException("编译失败");
        }

        // 4. 验证类文件
        File classFile = new File(outputDir.toFile(), "com/lhd_gm/scheduledtasksystem/job/" + className + ".class");
        if (!classFile.exists()) {
            throw new RuntimeException("类文件未生成: " + classFile.getAbsolutePath());
        }

        // 5. 加载类（使用独立类加载器）
        URLClassLoader classLoader = new URLClassLoader(
                new URL[]{ outputDir.toFile().toURI().toURL() },
                Thread.currentThread().getContextClassLoader()
        );
        return Class.forName("com.lhd_gm.scheduledtasksystem.job." + className, true, classLoader);
    }
}
